/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package accessor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Kirimi
 */
public class FactoryAccessor extends model.Model{
    public List<Factory> getAll(){
        List<Factory> retVal = new ArrayList<Factory>();
        Factory factory = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            String sql = "Select * from tblFactory";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                factory = new Factory();
                factory.setFactoryID(rs.getInt("factoryID"));
                factory.setFactoryName(rs.getString("name"));
                
                retVal.add(factory);
            }
            closeObject(rs);
            closeObject(ps);
            closeObject(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return retVal;
    }
    
    
    public int updateFactory(Factory factory){
        int retVal = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            String sql = "Update tblFactory set name = ? Where factoryID = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, factory.getFactoryName());
            ps.setInt(2, factory.getFactoryID());
            retVal = ps.executeUpdate();
            
            closeObject(ps);
            closeObject(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return retVal;
    }
    
    public Factory getFactoryByID(int factoryID){
        Factory factory = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            String sql = "Select * from tblFactory "
                    + " where tblFactory.factoryID = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, factoryID);
            rs = ps.executeQuery();
            if(rs.next()){
                factory = new Factory();
                factory.setFactoryID(rs.getInt("factoryID"));
                factory.setFactoryName(rs.getString("name"));
            }
            closeObject(rs);
            closeObject(ps);
            closeObject(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return factory;
    }
}
